package com.java110.mall.acct.cmd.integral;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.integral.IntegralDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.IIntegralSettingV1InnerServiceSMO;
import com.java110.intf.acct.IIntegralV1InnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.ListUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 查询用户积分
 */
@Java110Cmd(serviceCode = "integral.queryUserIntegral")
public class QueryUserIntegralCmd extends Cmd {

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IIntegralV1InnerServiceSMO integralV1InnerServiceSMOImpl;

    @Autowired
    private IIntegralSettingV1InnerServiceSMO integralSettingV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        String userId = CmdContextUtils.getUserId(context);
        Assert.hasLength(userId, "用户不存在");
        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);

        if (ListUtil.isNull(userDtos)) {
            throw new CmdException("用户不存在");
        }
        reqJson.put("link",userDtos.get(0).getTel());
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        String userId = CmdContextUtils.getUserId(context);
        IntegralDto integralDto = new IntegralDto();
        integralDto.setLink(reqJson.getString("link"));
        integralDto.setObjType(IntegralDto.OBJ_TYPE_PERSON);
        List<IntegralDto> integralDtos = integralV1InnerServiceSMOImpl.queryIntegrals(integralDto);
        JSONObject paramOut = new JSONObject();
        int integral = 0;
        if (!ListUtil.isNull(integralDtos)) {
            integral = Integer.parseInt(integralDtos.get(0).getAmount());
        }
        paramOut.put("integral", integral);

        //todo 计算成金额
        double money = integralSettingV1InnerServiceSMOImpl.computeMoney(integral);
        paramOut.put("integralMoney", money);

        context.setResponseEntity(ResultVo.createResponseEntity(paramOut));
    }
}
